package com.fee.master.service;




import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.provider.CallLog;
import android.util.Log;

import com.fee.master.MainActivity;
import com.fee.master.R;
import com.fee.master.db.ConfigCenter;
import com.fee.master.model.DayStat;
import com.fee.master.model.MonthStat;
import com.fee.master.util.Constants;
import com.fee.master.util.DateUtil;

/**
 * 电话日志观察对象
 * @author 
 *
 */
public class TeleDetailObserver extends ContentObserver {
	
	private static final String TAG = "DetailTeleObserver";
	
	private static final int DETAIL_SERVICE_STATUS_ID = 114;
	
	public static boolean registed = false;
	
	//需要在安装完后进行初始化
	public static int oldCount = 0;
	
	private Context context;
	
	private int paramDuration;
		
	private static final String[] TELE_PROJECTION = {
		CallLog.Calls.TYPE,CallLog.Calls.NUMBER,CallLog.Calls.DATE,CallLog.Calls.DURATION,
		CallLog.Calls.NEW,CallLog.Calls.CACHED_NAME,
	};

	public TeleDetailObserver(Context context,Handler handler) {
		super(handler);
		this.context = context;
	}
	
	public void onChange(boolean selfChange){
		Log.i(TAG, "on change");
		
		boolean callOut = false;
		boolean beAccept = false;	
		boolean newOutAcceptCall = false;
		ContentResolver content = context.getContentResolver();
		String orderBy = CallLog.Calls.DATE + " desc";
		Cursor cursor = content.query(CallLog.Calls.CONTENT_URI, TELE_PROJECTION, null, null, orderBy);
		int curCount = cursor.getCount();
		
		//需要是有新纪录才进行insert和统计操作
		if(cursor.moveToFirst() && curCount>oldCount){
				newOutAcceptCall = true;
				
				String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
				String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
				int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
				int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
				long ringTime = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));	
				String time = DateUtil.formatDate(ringTime, Constants.yyyyMMddHHmmss);
				//是否被接通
				beAccept = duration>0?true:false;
				paramDuration = duration;
				if(duration > 0){
					
					duration = formatDuration(duration);
					
					StringBuffer sb = new StringBuffer();					
					Log.d(TAG, sb.append("name:").append(name).append(",number:").append(number).append(",type:").append(type).append(",duration:").append(duration).toString());
					
//					ContentValues values = new ContentValues();
//					values.put(TeleDetail.PERSON_NAME, name);
//					values.put(TeleDetail.PERSON_NUMBER, number);
//					values.put(TeleDetail.TYPE, type);
//					values.put(TeleDetail.TIME, time);
//					values.put(TeleDetail.DURATION, duration);
//					context.getContentResolver().insert(TeleDetail.URI_TELE_DETAIL, values);
					
					//设置标志key
					String callType = "";
					if(type == CallLog.Calls.INCOMING_TYPE){
						callType = Constants.CALL_IN;
					}else if(type == CallLog.Calls.OUTGOING_TYPE){
						callType = Constants.CALL_OUT;
					}
					
					callOut = type == CallLog.Calls.OUTGOING_TYPE?true:false;
					
					//更新统计数据
					if(!callType.equals("")){
						String month = time.substring(0, 6);
						String day = time.substring(0,8);
						String mSelection = MonthStat.MONTH+" ='"+month+"' and "+MonthStat.KEY+"='"+callType+"'";
						String dSelection = DayStat.DAY+" ='"+day+"' and "+DayStat.KEY+"='"+callType+"'";
						
						//插入月统计数据
						ContentValues mValues = new ContentValues();
						mValues.put(MonthStat.MONTH, month);
						mValues.put(MonthStat.KEY, callType);
						mValues.put(MonthStat.NUM, duration);
						Cursor c = context.getContentResolver().query(MonthStat.URI_MONTH_STAT, null, mSelection, null, null);
						
						if(c!= null && c.getCount()>0){
							context.getContentResolver().update(MonthStat.URI_MONTH_STAT, mValues, null, null);
						}else{							
							context.getContentResolver().insert(MonthStat.URI_MONTH_STAT, mValues);
						}
						c.close();
						
						//插入日统计数据
						ContentValues dValues = new ContentValues();
						dValues.put(DayStat.DAY, day);
						dValues.put(DayStat.KEY, callType);
						dValues.put(DayStat.NUM, duration);
						
						Cursor dc = context.getContentResolver().query(DayStat.URI_DAY_STAT, null, dSelection, null, null);
						if(dc!= null && dc.getCount()>0){
							context.getContentResolver().update(DayStat.URI_DAY_STAT, dValues, null, null);
						}else{							
							context.getContentResolver().insert(DayStat.URI_DAY_STAT, dValues);
						}
						dc.close();	
					}
				}	
			}
		cursor.close();
		
		//更新oldCount，下次比较就是更新后的值
		oldCount = curCount;
		
		//send stat
		String installDay = ConfigCenter.getValue(context, Constants.KEY_INSTALL_DAY, "0");
		String today = DateUtil.getCurrentDate("yyyyMMdd");
		Log.d("back", "install day="+installDay);

		
		
		if(callOut && beAccept && newOutAcceptCall){
			//检查告警
			if(checkOverMaxTime()){				
				showNotify();
			}
			
//			if(ConfigCenter.getValue(context, Constants.ENABLE_TIME_NOTIFY, true)){
//				Intent i = new Intent(context,NotifyView.class);
//				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//				i.putExtra("duration", paramDuration);
//				context.startActivity(i);
//			}
		}
	}
	
	private int formatDuration(int value){
		if(value%60 !=0){
			return (value/60 + 1)*60;
		}else{
			return value;
		}
	}
	
	private boolean checkOverMaxTime(){
		String max = ConfigCenter.getValue(context, Constants.KEY_WARN_CALL_TIME, "0");
		if("".equals(max) || "0".equals(max)){
			return false;
		}else{
			int curNum = 0;
			String selection = MonthStat.MONTH+"="+ DateUtil.getCurrentDate("yyyyMM");
			selection = selection +" and "+MonthStat.KEY+"='"+Constants.CALL_OUT+"'";
	        Cursor c = context.getContentResolver().query(MonthStat.URI_MONTH_STAT, null, selection, null, null);
	        if(c.moveToFirst()){
	        	curNum = c.getInt(c.getColumnIndex(MonthStat.NUM));	        	
	        }
	        c.close();
	        if(curNum > Integer.valueOf(max)*60){
	        	return true;
	        }else{
	        	return false;
	        }
		}		
	}
	
	private void showNotify(){
		NotificationManager nfManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification nf = new Notification();
		nf.icon = R.drawable.icon;
		nf.tickerText = context.getResources().getString(R.string.notify_desc);
		PendingIntent contentIntent = PendingIntent
				.getActivity(context, 0, new Intent(context,MainActivity.class), 0);
		
		String max = ConfigCenter.getValue(context, Constants.KEY_WARN_CALL_TIME, "0");
		String title = context.getResources().getString(R.string.app_name);
		String desc = context.getResources().getString(R.string.notify_desc)+":"+max+"分钟";
		nf.setLatestEventInfo(context, title,desc, contentIntent);
		nf.flags = Notification.FLAG_NO_CLEAR;

		nfManager.notify(DETAIL_SERVICE_STATUS_ID, nf);
	}
}
